<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-goods"></i> 拼团管理
                </el-breadcrumb-item>
                <el-breadcrumb-item>拼团列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row>
                    <el-col :span="6">
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            class="handle-del mr10"
                            @click="delAllSelection"
                        >批量删除</el-button>
                        <el-button
                            type="primary"
                            icon="el-icon-circle-plus-outline"
                            class="handle-del mr10"
                            @click="handleEdit(-1,null)"
                        >添加拼团</el-button>
                    </el-col>
                    <el-col :span="16" style="display:flex;justify-content: center;">
                        <el-select
                            v-model="query.sort"
                            placeholder="选择排序方式"
                            style="width:120px;margin-right:10px"
                        >
                            <el-option key="1" label="正序" value="1"></el-option>
                            <el-option key="2" label="倒序" value="2"></el-option>
                        </el-select>
                        <el-input
                            v-model="query.name"
                            style="width:120px"
                            placeholder="拼团名称"
                            class="handle-input mr10"
                        ></el-input>
                        <el-input
                            v-model="query.id"
                            style="width:120px"
                            placeholder="拼团ID"
                            class="handle-input mr10"
                        ></el-input>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table
                :data="tableData"
                border
                v-loading="loading"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="60" sortable align="center"></el-table-column>
                <el-table-column label="拼团名称" prop="name" align="center"></el-table-column>
                <el-table-column label="副标题描述" align="center">
                    <template slot-scope="scope">
                        <el-popover
                            placement="bottom"
                            title="拼团描述"
                            width="200"
                            trigger="click"
                            :content="scope.row.desc"
                        >
                            <el-link type="primary" slot="reference" :underline="false">查看</el-link>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="列表图" align="center">
                    <template slot-scope="scope">
                        <el-image
                            class="table-td-thumb"
                            :src="scope.row.banner[0]"
                            :preview-src-list="scope.row.banner"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="详情图" align="center">
                    <template slot-scope="scope">
                        <el-image
                            class="table-td-thumb"
                            :src="scope.row.images[0]"
                            :preview-src-list="scope.row.images"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="拼团价格" prop="price" align="center"></el-table-column>
                <el-table-column label="原价" prop="price" align="center"></el-table-column>
                <!--<el-table-column label="第一次返还" align="center">-->
                    <!--<template slot-scope="scope">-->
                        <!--<span>{{scope.row.back_one}}%</span>-->
                    <!--</template>-->
                <!--</el-table-column>-->
                <!--<el-table-column label="第二次返还" align="center">-->
                    <!--<template slot-scope="scope">-->
                        <!--<span>{{scope.row.back_two}}%</span>-->
                    <!--</template>-->
                <!--</el-table-column>-->
                <!--<el-table-column label="第三次返还" align="center">-->
                    <!--<template slot-scope="scope">-->
                        <!--<span>{{scope.row.back_three}}%</span>-->
                    <!--</template>-->
                <!--</el-table-column>-->
                <el-table-column label="拼团人数" prop="num" align="center"></el-table-column>
                <el-table-column label="拼中人数" prop="jackpot_num" align="center"></el-table-column>
                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <span
                            :style="{color:scope.row.status==1?'#67C23A':'#E6A23C'}"
                        >{{scope.row.status==1?'已上架':'已下架'}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="修改时间"></el-table-column>
                <el-table-column prop="created_at" label="添加时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            @click="updateStatus(scope.row.id,scope.$index,scope.row.status)"
                            :icon="scope.row.status==1?'el-icon-lx-attentionforbid':'el-icon-lx-attention'"
                            type="text"
                            :style="{color:scope.row.status!=1?'#67C23A':'#E6A23C'}"
                        >{{ scope.row.status==1?'下架':'上架' }}</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 添加编辑弹出 -->
        <el-dialog v-dialogDrag :title="formName" :visible.sync="editVisible" width="1000px">
            <el-form :model="edit" label-width="100px">
                <el-form-item label="名称" style="width:480px">
                    <el-input
                        type="text"
                        v-model="edit.name"
                        maxlength="30"
                        minlength="2"
                        placeholder="请输入名称"
                    ></el-input>
                </el-form-item>
                <el-form-item label="描述" style="width:480px">
                    <el-input
                        type="text"
                        v-model="edit.desc"
                        maxlength="30"
                        minlength="2"
                        placeholder="请输入描述"
                    ></el-input>
                </el-form-item>
                <el-form-item label="拼团分类" v-model="edit.pcate" style="width:480px">
                   <template>
                    <el-select v-model="edit.pcate" placeholder="请选择分类" @change="getgoods">
                      <el-option
                        v-for="item in pcate"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                </el-form-item>
                <el-form-item label="拼团商品" v-model="edit.pcate" style="width:480px">
                   <template>
                    <el-select v-model="edit.goods_id" placeholder="请选择商品" @change="choseGoods" >
                      <el-option
                        v-for="item in pcate_goods"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                </el-form-item>
                <el-form-item label="拼团人数" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.num"
                        maxlength="30"
                        minlength="2"
                        placeholder="请输入拼团人数"
                    ></el-input>
                </el-form-item>
                <el-form-item label="拼中人数" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.jackpot_num"
                        maxlength="10"
                        minlength="2"
                        placeholder="请输入拼中人数"
                    ></el-input>
                </el-form-item>
              <!--   <el-form-item label="BUC" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.buc"
                        placeholder="请输入buc"
                    ></el-input>
                </el-form-item>-->
                <el-form-item label="积分" style="width:480px">
                    <el-input
                            type="number"
                            v-model="edit.coin"
                            placeholder="请输入积分"
                    ></el-input>
                </el-form-item>
     <!--           <el-form-item label="拼中锁定百分比" style="width:480px">
                    <div class="standard">
                        <el-input
                                v-model="edit.coin_yes"
                                type="number"
                                maxlength="30"
                                placeholder="请输入拼中锁定百分比（填写1-100）"
                        ></el-input>%
                    </div>
                </el-form-item>
                <el-form-item label="不拼中返佣百分比" style="width:480px">
                    <div class="standard">
                        <el-input
                                v-model="edit.coin_no"
                                type="number"
                                maxlength="30"
                                placeholder="不拼中返佣百分比（填写1-100）"
                        ></el-input>%
                    </div>
                </el-form-item>-->

                <el-form-item label="价格" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.price"
                        maxlength="10"
                        minlength="2"
                        placeholder="请输入价格"
                    ></el-input>
                </el-form-item>
                <el-form-item label="原价" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.original_price"
                        maxlength="30"
                        minlength="2"
                        placeholder="请输入原价"
                    ></el-input>
                </el-form-item>
                <!--<el-form-item label="第一次返还" style="width:480px">-->
                    <!--<div class="standard">-->
                        <!--<el-input-->
                            <!--v-model="edit.back_one"-->
                            <!--type="number"-->
                            <!--maxlength="30"-->
                            <!--placeholder="请输入第一次返还百分比"-->
                        <!--&gt;</el-input>%-->
                    <!--</div>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="第二次返还" style="width:480px">-->
                    <!--<div class="standard">-->
                        <!--<el-input-->
                            <!--v-model="edit.back_two"-->
                            <!--type="number"-->
                            <!--maxlength="30"-->
                            <!--placeholder="请输入第二次返还百分比"-->
                        <!--&gt;</el-input>%-->
                    <!--</div>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="第三次返还" style="width:480px">-->
                    <!--<div class="standard">-->
                        <!--<el-input-->
                            <!--v-model="edit.back_three"-->
                            <!--type="number"-->
                            <!--maxlength="30"-->
                            <!--placeholder="请输入第三次返还百分比"-->
                        <!--&gt;</el-input>%-->
                    <!--</div>-->
                <!--</el-form-item>-->
                <el-form-item label="每天开团次数" style="width:480px">
                    <el-input
                        type="number"
                        v-model="edit.day_num"
                        maxlength="10"
                        minlength="2"
                        placeholder="请输入每天可发起拼团的次数"
                    ></el-input>
                </el-form-item>
                <el-form-item label="每天开启拼团时间" style="width:480px">
                    <el-time-picker
                        is-range
                        v-model="dateValue"
                        value-format="HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        placeholder="选择时间范围"
                        @change="changeTime"
                    ></el-time-picker>
                </el-form-item>

                <el-form-item label="排序" style="width:480px">
                    <el-input
                        v-model="edit.sort"
                        maxlength="2"
                        minlength="1"
                        type="number"
                        placeholder="请输入排序"
                    ></el-input>
                </el-form-item>
                <el-form-item label="是否上架" prop="status">
                    <el-switch v-model="edit.status" active-value="1" inactive-value="2"></el-switch>
                </el-form-item>
                <el-form-item label="商品图片" class="form-item">
                    <el-upload
                        class="upload-demo"
                        ref="addUploads"
                        drag
                        :limit="6"
                        :auto-upload="true"
                        show-file-list
                        accept="image/*"
                        :on-success="uploadSuccess"
                        :on-error="uploadError"
                        :on-preview="uploadPreview"
                        :action="api.upload_img_url"
                        list-type="picture-card"
                        :on-exceed="uploadExceed"
                        :file-list="edit.banner_url"
                        multiple
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="详情图" class="form-item">
                    <el-upload
                        class="upload-demo"
                        ref="addUploads"
                        drag
                        :limit="15"
                        :auto-upload="true"
                        show-file-list
                        accept="image/*"
                        :on-success="imagesUploadSuccess"
                        :on-error="uploadError"
                        :on-preview="uploadPreview"
                        :action="api.upload_img_url"
                        list-type="picture-card"
                        :on-exceed="uploadExceed"
                        :file-list="edit.images_url"
                        multiple
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <div class="dialog-footer-but">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleSave">确 定</el-button>
                </div>
            </span>
        </el-dialog>
        <!-- 预览图片 -->
        <div class="previews" @click="closePreviews" v-if="windowsPopVisible">
            <img :src="windowsPopUrl" title="点击即可关闭预览" />
        </div>
    </div>
</template>

<script>

export default {
  name: 'goods',
  data () {
    return {
      query: {
        name: '',
        id: '',
        page: 1,
        pageSize: 10,
        status: '',
        sort: '1'
      },
      formName: '添加商品',
      editVisible: false,
      windowsPopVisible: false,
      windowsPopUrl: '',
      loading: false,
      tableData: [],
      multipleSelection: [],
      pageTotal: 0,
      delList: [],
      dateValue: [new Date(2021, 1, 1, 0, 0), new Date(2021, 1, 1, 23, 59)],
      edit: {
        start_end_time: [], day_num: ''
      },
      idx: -1,
      id: -1,
      pcate:[],
      pcate_goods:[],
      //获取列表请求
       getPcate: function(){
        let that = this;
        this.api.get('pcate', {status:1}, res => {
            that.pcate = res.data
        })
      },
      getList: function () {
        let that = this;
        this.api.get('group', this.query, res => {
          for (let i in res.data.list) {
            res.data.list[i].status = res.data.list[i].status + '';
          }
          that.tableData = res.data.list;
          that.query.page = res.data.page;
          that.query.pageSize = res.data.pageSize;
          that.pageTotal = res.data.pageTotal;
        }, undefined, undefined, this);
      },
      //删除请求
      delLists: function (ids, msg) {
        let that = this;
        if (ids.length < 1) {
          this.$message.error('请选择删除的数据');
          return false;
        }
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        }).then(() => {
          that.api.delete('delGroup', { ids: ids }, res => {
            that.query.page = 1;
            that.getList();
            that.multipleSelection = [];
            that.$message.success(msg);
          }, undefined, undefined, this);
        }).catch(() => { });
      }
    };
  },
  watch: {
    $route: {

      handler (to, from) {
        if (to && to.params && to.params.group_to_id) {
          this.query.id = to.params.group_to_id;
          this.getList();
        }
      },
      // 深度观察监听
      deep: true

    }
  },
  created () {
    this.getList();
    this.getPcate()
  },
  methods: {
    //设置商品属性
    goodsChange (id, index, key) {
      this.api.put('groupSetGoods', { id: id, key: key }, res => {
        this.$message.success(res.msg);
        this.tableData[index][key] = res.data.val;

      });
    },
    getgoods(e){
      let _this=this
      this.api.post('getgoodsforcate', {cate:e}, res => {
        _this.pcate_goods = res.data

      });
    },
    choseGoods(e){
      let _this=this;
      let goods = this.pcate_goods;
      let images = [];
      let banner = [];
      for(var i in goods){
        if(e == goods[i].id){
            _this.edit.price = goods[i].price
            for (let j in goods[i].images) {
              images.push({
                name: '预览',
                url: goods[i].images[j]
              });
            }
            for (let k in  goods[i].banner) {
              banner.push({ 
                name: '预览',
                url:  goods[i].banner[k]
              });
            }
        }
      }
      _this.edit.banner_url = banner
      _this.edit.images_url = images
     
    },
    handleEdit (index, row) {
      if (index < 0) {
        this.formName = '添加拼团';
        this.edit = {
          name: '', sort: 10, start_end_time: [], day_num: ''
        };
      } else {
        this.formName = '编辑拼团';
        let banner = [];
        for (let i in row.banner) {
          banner[banner.length] = {
            name: '预览',
            url: row.banner[i]
          };
        }
        
          this.edit = row;
        this.edit.banner_url = banner;
        let images = [];
        for (let i in row.images) {
          images[images.length] = {
            name: '预览',
            url: row.images[i]
          };
        }
        this.dateValue = [row.start_time , row.end_time],
        this.edit = row;
        this.edit.banner_url = banner;
        this.edit.images_url = images;
        this.getgoods(row.pcate)
        this.edit.goods_id = row.goods
      }
      this.editVisible = true;
      
      
    },

    handleSave () {
      if (this.edit && this.edit.id) {
        this.api.put('editGroup', this.edit, res => {
          this.$message.success(res.msg);
          this.editVisible = false;
          this.getList();
        });
      } else {
        this.api.post('addGroup', this.edit, res => {
          this.$message.success(res.msg);
          this.editVisible = false;
          this.getList();
        });
      }
    },

    /**
     * 起始日期选择事件
     */
    changeTime (e) {
      if (!e) {
        return false;
      }
      console.log(e);
      this.edit.start_end_time = [e[0], e[1]];
    },

    /***
     * 超出上传限制事件
     */
    uploadExceed () {
      this.$message.error('只能上传6张图片');
    },

    /***
     * 添加banner预览
     */
    uploadPreview (file) {
      this.windowsPopVisible = true;
      this.windowsPopUrl = file.response.data.url;
    },

    /***
     * 关闭预览
     */
    closePreviews () {
      this.windowsPopVisible = false;
    },

    /***
     * 添加banner上传成功事件
     */
    uploadSuccess (response, file, fileList) {
      console.log(fileList);
      if (response.code != 1000) {
        this.$message.error(response.msg);
        return false;
      }
      let banner = [];
      for (let i in fileList) {
        banner[banner.length] = {name:'预览',url:fileList[i].response.data.url};
      }
      this.edit.banner_url = banner;
    },
    imagesUploadSuccess (response, file, fileList) {
     
      if (response.code != 1000) {
        this.$message.error(response.msg);
        return false;
      }
      let images = [];
      for (let i in fileList) {
        images[images.length] = {name:'预览',url:fileList[i].response.data.url};
      }
      this.edit.images_url = images;
      console.log(this.edit)
    },
    /***
     * 添加banner上传失败事件
     */
    uploadError (response, file, fileList) {
      this.$message.error('上传失败');
    },

    // 触发搜索按钮
    handleSearch () {
      this.$set(this.query, 'page', 1);
      this.getList();
    },

    /**
     * 操作状态
     */
    updateStatus (id, index, status) {
      let str = status == 1 ? '下架' : '上架';
      this.$confirm('确定要' + str + '吗？', '提示', {
        type: 'info'
      }).then(() => {
        this.api.put('groupStatus', { id: id, status: status }, res => {
          this.$message.success(res.msg);
          if (res.data.status == 4) {
            this.getList();
          }
          this.tableData[index].status = res.data.status;

        });
      }).catch(() => { });

    },


    // 多选操作
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },

    // 删除操作
    handleDelete (index, row) {
      this.delLists([row.id], '删除成功');
    },
    //批量删除
    delAllSelection () {
      const length = this.multipleSelection.length;
      let str = '';
      this.delList = this.delList.concat(this.multipleSelection);
      let ids = [];
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + ' ';
        ids.push(this.multipleSelection[i].id);
      }
      this.delLists(ids, `删除了${str}`);
    },

    // 分页导航
    handlePageChange (val) {
      this.$set(this.query, 'page', val);
      this.getList();
    },




  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.t-tag {
    cursor: pointer;
}
.standard {
    width: 100%;
    height: auto;
    display: flex;
    flex-flow: nowrap row;
    align-items: center;
}
.standard > div {
    margin-right: 5px;
}
</style>
